import cTitle from "components/title";
import { scrollMixin } from "utils/mixin";
import goodsItem from "../sachertorteComm/goodsItem";
import screenPopup from "../sachertorteComm/screenPopup";
import sarchHistory from "components/searchHistory";
export default {
  components: {
    cTitle,
    goodsItem,
    sarchHistory,
    screenPopup
  },
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      search: "",
      screenShow: false,
      goodsList: [],
      cakeType: [
        {
          type: "",
          text: "全部"
        },
        {
          type: 1,
          text: "4-5人食"
        },
        {
          type: 2,
          text: "6-9人"
        },
        {
          type: 3,
          text: "10-12人"
        },
        {
          type: 4,
          text: "12人以上"
        }
      ],
      getBrand: [],

      query: {
        page: 1,
        city: "",
        order_field: "",
        order_by: "",
        cake_type: "",
        cake_price_max: "",
        cake_price_min: "",
        snacks_price_max: "",
        snacks_price_min: ""
      },
      page: 1,
      totalPage: 0,
      isLoadMore: true,
      brandsId: "",
      categorysId: "",
      keyword: "",
      priceSnacks: [
        {
          type: ["", ""],
          text: "全部"
        },
        {
          type: [20, 99],
          text: "20-99"
        },
        {
          type: [100, 199],
          text: "100-199"
        },
        {
          type: [199, ""],
          text: "199以上"
        }
      ],
      cakePriceArr: [
        {
          type: ["", ""],
          text: "全部"
        },
        {
          type: [100, 200],
          text: "100-200"
        },
        {
          type: [200, 300],
          text: "200-300"
        }
      ],
      categorys: [],
      indexType: 0, //尺寸选择
      storageName: "sachertorte", // 蛋糕显示历史搜索记录
      showHistory:false,
      total_page:0,
      background_color:'#ffc11e'
    };
  },
  activated() {
    if(this.$route.query.city) {
      this.query.city = this.$route.query.city;
    }
    this.query.page = 1;
    this.fun
      .getLocation()
      .then(res => {
        console.log(res);
        this.locationStatus = true;
        if (this.query.city === "") {
          this.query.city = res.city;
        }
        this.categorysList();
        this.goodsByList();
        this.getBrandsData();
      })
      .catch(err => {
        console.log(err);
        this.categorysList();
        this.goodsByList();
        this.getBrandsData();
        this.locationStatus = false;
      });
  },
  methods: {
    searchBlur() {
      this.showHistory = false;
      // this.getSosoHeight();
    },
    hidebox(){
      this.screenShow = false;
      this.searchHistoryList = window.localStorage.getItem(this.storageName) ? JSON.parse(window.localStorage.getItem(this.storageName)) : [];
      if (this.searchHistoryList.length > 0) {
        this.showHistory = true;
      }
    },
    searchChange(value) {
      //搜索事件
      console.log(value);
      this.query.page = 1;
      this.keyword = value;
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.debounce(this.goodsByList());
      }, 500);
    },
    popularity() {
      //选择人气
      this.query.page = 1;
      this.query.order_by = "";
      this.query.order_field = "popularity";
      this.isLoadMore = true;
      this.goodsByList();
    },
    salesClick(sort) {
      let sortValue = "asc";
      this.sortSwicth(sort, sortValue, "show_sales"); //处理判断倒序，正序
    },
    screenClose() {
      this.screenShow = false;
    },
    sortSwicth(sort, sortValue, field) {
      switch (sort) {
        case "asc":
          sortValue = "desc";
          break;
        case "desc":
          sortValue = "asc";
          break;
      }
      this.query.page = 1;
      this.query.order_by = sortValue;
      this.query.order_field = field;
      this.isLoadMore = true;
      this.goodsByList();
    },
    // 点击tag搜索
    serachTag(data) {
      this.keyword = data;
      this.searchOn();
    },
    searchOn() {
      //搜索
      // this.keyword = value;
      if(!this.keyword) return
      this.query.page = 1;
      if (this.timer) clearTimeout(this.timer);
      // 添加搜索记录
      if (this.$refs.searchHistory) {
        this.$refs.searchHistory.appendKeywords(this.keyword);
      }
      this.timer = setTimeout(() => {
        this.debounce(this.goodsByList());
      }, 500);
    },
    priceClick(sort) {
      //选择价格
      let sortValue = "asc";
      this.sortSwicth(sort, sortValue, "price"); //处理判断倒序，正序
    },
    screeningPopup() {
      this.screenShow = true;
      console.log(this.screenShow);
    },
    debounce(fn, delay) {
      let last, deferTimer;
      return function(args) {
        let that = this;
        let _args = arguments;
        let now = +new Date();
        if (last && now < last + delay) {
          clearTimeout(deferTimer);
          deferTimer = setTimeout(function() {
            last = now;
            fn.apply(that, _args);
          }, delay);
        } else {
          last = now;
          fn.apply(that, _args);
        }
      };
    },
    screenClick(data) {
      console.log(data);
      //筛选完成
      let { brandValue, cakeValue, categoryValue, priceValue, cakePirceValue } = data;
      this.screenShow = false;
      this.isLoadMore = true;
      this.brandsId = brandValue;
      console.log(this.brandsId);
      this.categorysId = categoryValue;
      this.query.cake_type = cakeValue;
      this.query.page = 1;
      this.query.cake_price_min = cakePirceValue[0];
      this.query.cake_price_max = cakePirceValue[1];
      this.query.snacks_price_min = priceValue[0];
      this.query.snacks_price_max = priceValue[1];
      this.goodsByList();
    },
    getBrandsData() {
      let query = {
        city: this.query.city
      };
      $http.get("plugin.yz-supply-cake.frontend.goods.goods.getBrand", query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.getBrand = res;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    categorysList() {
      $http.get("plugin.yz-supply-cake.frontend.index.index.getCategorys", {}, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let list = res;
            this.categorys = list;
            let info_basic = JSON.parse(localStorage.getItem("yz_basic_info"));
            this.background_color = info_basic.theme_color;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    goodsByList() {
      let urlStr = "plugin.yz-supply-cake.frontend.goods.goods.getGoodsList";
      urlStr += `&search[brand_id]=${this.brandsId}`;
      urlStr += `&search[category]=${this.categorysId}`;
      urlStr += `&search[keyword]=${this.keyword}`;
      console.log(this.$route.query.store_id)
      if(this.$route.query.store_id){
        urlStr += `&yz_supply_cake_store_id=${this.$route.query.store_id}`;
      }
      $http.get(urlStr, this.query, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.isLoadMore = true;
            this.total_page = res.last_page;
            if (!this.total_page) {
              this.page = 0;
            }
            this.goodsList = res.data;
          } else {
            this.query.page = this.query.page - 1;
            this.isLoadMore = false;
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    //获取更多数据
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.query.page >= this.total_page) {
        return;
      } else {
        this.query.page = this.query.page + 1;
        let urlStr = "plugin.yz-supply-cake.frontend.goods.goods.getGoodsList";
        urlStr += `&search[brand_id]=${this.brandsId}`;
        urlStr += `&search[category]=${this.categorysId}`;
        urlStr += `&search[keyword]=${this.keyword}`;
        if(this.$route.query.store_id){
          urlStr += `&yz_supply_cake_store_id=${this.$route.query.store_id}`;
        }
        $http.post(urlStr, this.query, "加载中").then(
          res => {
            this.isLoadMore = true;
            if (res.result === 1) {
              let myData = res.data.data;
              this.goodsList = [...this.goodsList, ...myData]; //数组拼接
            } else {
              this.query.page = this.query.page - 1;
              this.isLoadMore = false;
            }
          },
          function(response) {
            console.log("response", response);
            // error callback
          }
        );
      }
    }
  }
};
